{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Driving for Cheaper Gas\n",
    "by Michael Lamoureux (University of Calgary) and Hongmei Zhu (York University)\n",
    "\n",
    "Teachers' Workshop: Bringing computational thinking and mathematical modeling into the \n",
    "Ontario secondary curriculums, Feb. 21-22, 2019, York University; Jointly organized by  Callysto and Math for Real"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## A General Problem \n",
    "Most drivers have a “usual” region in which they do most of their driving. However, gas prices may vary widely so that gas may be substantially cheaper somewhere other than within that usual region. Would it be more economical to go to a station out of the normal route to buy cheaper gas? \n",
    "\n",
    "Thus, the general question we wish to address is \"is it cost effective to drive further for cheaper gas?\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Consider a specific problem\n",
    "\n",
    "Suppose there is an Esso station on your normal route that sells gas for 98.9 per liter.  A Costco station 5 km off your route sells gas for 89.9 per liter. \n",
    "\n",
    "Your car gets 20 km/L. Should you travel the extra distance to buy 40 liters gas at that Costco station? "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Main factors that affect our decision\n",
    "We name them in a variable list as below:\n",
    "\n",
    "$P_A$ : the price per liter at nearest gas station A along our route \n",
    "\n",
    "$P_B$: the price per liter at the station B we are considering. \n",
    "\n",
    "$D$: represent the distance in km from the normal route that must be driven to get to the gas station and back to normal route. \n",
    "\n",
    "$E$: represent efficiency of the vehicle in km per liter. \n",
    "\n",
    "$V$: represent the number of liters of gas we purchase when we buy gas "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## How to make decision?  \n",
    "\n",
    "If we gas up at Station A, the gas station on the normal route, the cost is $$P_A * V$$ \n",
    "\n",
    "If we gas up at Station B (Costco) with cheaper price, we will need to purchase $$ V + D/E$$ liters of gas to leave the equivalent amount of gas in the tank. The total cost is $$P_B * (V + \\frac{D}{E})$$. \n",
    "\n",
    "Hence, the decision about whether we shall drive for cheaper gas is determined by the fact that if \n",
    "$$P_A * V > P_B * (V + \\frac{D}{E})?$$ \n",
    "equivalently, whether $$P_B < P_A * \\frac{V}{(V + D/E)}?$$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "slideshow": {
     "slide_type": "skip"
    }
   },
   "outputs": [],
   "source": [
    "# Jupyter widgets give us the interactive components\n",
    "from ipywidgets import interact\n",
    "\n",
    "# For plotting\n",
    "import matplotlib.pyplot as plt\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "skip"
    }
   },
   "source": [
    "## Making a simple App to help you decide whether it is worth driving further for cheaper gas? "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "slideshow": {
     "slide_type": "skip"
    }
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "7cf1c1d578ee44c39afa8e99174b68d2",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "interactive(children=(FloatSlider(value=98.9, description='PA', max=200.0, min=50.0), FloatSlider(value=89.9, …"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "def update(PA=98.9, PB=89.9, V=40, D=10, E=20):\n",
    "    \n",
    "    #calculate the coefficient C\n",
    "    C = V/(V+D/E)\n",
    "   \n",
    "    print(\"Driving for Cheaper Gas Decision:\")\n",
    "    if (PB < PA*C):\n",
    "        # calculate total savings in dollars\n",
    "        save = (PA*V - PB*(V+D/E))/100.0 \n",
    "        # convert it to a string with 2 decimal as a currency \n",
    "        txt = str('save $%.2f'% save)\n",
    "        \n",
    "        # print the Yes decision \n",
    "        print(\"Yes! In total you will \" + txt)\n",
    "        \n",
    "        # write the decision on the graph\n",
    "        plt.text(PA+20, PB, txt, {'color': 'g', 'fontsize': 16})\n",
    "    else:\n",
    "        print(\"No, not worth it!\")\n",
    "    \n",
    "    # draw the line P*C where P is a price variable for Station A  \n",
    "    plt.plot([0,250], [0,C*250], lw=2, color='b')\n",
    "\n",
    "# label the Yes region and No region and plot the Price in the plot. \n",
    "    plt.text(200, 50, 'Yes',\n",
    "         {'color': 'g', 'fontsize': 24, 'ha': 'center', 'va': 'center',\n",
    "          'bbox': dict(boxstyle=\"round\", fc=\"w\", ec=\"k\", pad=0.2)})\n",
    "    plt.text(50, 200, 'No',\n",
    "         {'color': 'r', 'fontsize': 24, 'ha': 'center', 'va': 'center',\n",
    "          'bbox': dict(boxstyle=\"round\", fc=\"w\", ec=\"k\", pad=0.2)})\n",
    "    # Draw a circle point of size 50 at the location (PA, PB) indicating current price at Station B\n",
    "    plt.scatter(PA, PB, s=50, c='k', marker='o')\n",
    "    \n",
    "    # Adjust the y-axis range and label the axes \n",
    "    plt.ylim([0, 250])\n",
    "    plt.xlabel(\"Gas Price at Station A\")\n",
    "    plt.ylabel(\"Gas Price at Station B\");\n",
    "\n",
    "# update the values in the slider and then re-plot \n",
    "interact(update, PA=(50.0,200.0,0.1), PB=(50.0,200.0,0.1), V=(0.0,100.0,0.5), D =(0.0,50.0,0.1), E = (1,50,1));"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## What if \n",
    "You can certainly use this app to help you make decision on whether it is worthwhile to drive for cheaper gas. With this simple model, you can modify your model and provide an decision for different situations. For instance, you can ask \n",
    "\n",
    "A) What if you want to put 20 liters of gas instead of 40 liters? \n",
    "\n",
    "B) what if your friends car gets 10 km/L; Should your friend travel the extra distance to buy gas at that Costco station for 20 lite?\n",
    "\n",
    "C) If V, D, and E remain the constant, can you derive a simple rule to make your decision? \n",
    "\n",
    "D) Is it truly worth going the extra mile for cheaper gas if you consider the time value of extra driving? \n",
    "\n",
    "E) What if you travel during rush hours? What if there is a long line-up at Costco gas station? \n",
    "\n",
    "F) What if there a number of gas stations within a neighborthood that offer various cheaper prices? Can we select a station that is most cost-effective? "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Reference: \n",
    "Maria L. Hernández, Rachel Levy, Mathew D. Felton-Koestler,and Rose Mary Zbiek, [\"Mathematical modeling in high school curriculum\"](https://drive.google.com/open?id=19OR664R47aKAo5QgsAC6cpRFMRTsPkp2), MATHEMATICS TEACHER | Vol. 110, No. 5 • December 2016/January 2017\n",
    "### Acknowledgement: \n",
    "We highly appreciate the support and great help from India Heisz, Callysto, in the development of the Jupyter notebooks for the workshop "
   ]
  }
 ],
 "metadata": {
  "celltoolbar": "Raw Cell Format",
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
